package com.chunuo.aclservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chunuo.aclservice.entity.Role;
import com.chunuo.aclservice.entity.UserRole;
import com.chunuo.aclservice.mapper.UserRoleMapper;
import com.chunuo.aclservice.service.RoleService;
import com.chunuo.aclservice.service.UserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-08-05
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Autowired
    private RoleService roleService;

    /**
     * 批量保存  用户绑定 角色
     * @param userId
     * @param roleIds
     */
    @Override
    public void batchBind(String userId, List<String> roleIds) {
        //先删除原先绑定的角色
        this.remove(new QueryWrapper<UserRole>().eq("user_id", userId));

        List<UserRole> userRoleList = new ArrayList<>();
        for(String roleId : roleIds) {
            if(StringUtils.isEmpty(roleId)) continue;
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);

            userRoleList.add(userRole);
        }
        this.saveBatch(userRoleList);

    }

    // 获取用户已绑定的角色同时获取所有角色
    @Override
    public Map getUserBindRole(String userId) {
        // 获取所有的角色信息
        List<Role> roleList = roleService.list(null);
        //根据用户id获取用户角色关系
        List<UserRole> userRoles = this.list(new QueryWrapper<UserRole>().eq("user_id", userId).select("role_id"));

        // 将角色id封装到List中
        List<String> roleIds = null;
        if(userRoles!=null&&userRoles.size()>0){
            roleIds = userRoles.stream().map(obj -> {
                return obj.getRoleId();
            }).collect(Collectors.toList());
        }
        System.out.println("roleIds ====== "+roleIds);

        //已分配的角色
        List<Role> assignRoles = new ArrayList<Role>();
        if(roleIds!=null&&roleIds.size()>0){
            for (Role role : roleList) {
                //已分配
                if(roleIds.contains(role.getId())) {
                    assignRoles.add(role);
                }
            }
        }

        Map map = new HashMap();
        map.put("assignRoles", assignRoles);
        map.put("allRolesList", roleList);
        return map;
    }
}
